<template>
  <div>
    <div v-show="!showEdit&&!showDetail">
      <search-form
        :search-config="searchConfig"
        :label-width="150"
        @clear="clearSearch"
        @search="handleSearch"
      />
      <table-box
        ref="refTable"
        table-size="mini"
        :table-config="tableConfig"
        show-selection
        dragable
        :selected-arry.sync="tableSelected"
        :other-filters="otherFilters"
        @btnOperate="btnOperate"
        @selection-change="selectionChangeHandle"
      />
    </div>
    <div>
      <import-files v-if="importVisible" title="导入" :visible.sync="importVisible" :config="fileImportConfig" @success="refreshTable" />
      <export-files v-if="exportVisible" title="导出" :config="exportConfig" :visible.sync="exportVisible" />
    </div>
    <edit-form v-if="showEdit" :id="activeDataId" :page-show.sync="showEdit" @success="refreshTable" />
    <add-item v-if="showAddItem" :id="activeDataId" ref="formDlg" :detail-data="todayFillDetail" :channel-task-code="channelTaskCode" :visible.sync="showAddItem" @success="refreshTable" />
    <detail-page v-if="showDetail" :id="activeDataId" :page-show.sync="showDetail" />

  </div>
</template>
<script>
import editForm from './editForm.vue'
import addItem from './addItem.vue'
import detailPage from './detail.vue'
import { nowTime } from '@/utils/tool'
import { queryDailyFill } from '@/api/channelTask'

export default {
  name: 'ChannelTask',
  components: { editForm, addItem, detailPage },
  data() {
    return {
      exportVisible: false,
      importVisible: false,
      showAddItem: false,
      tableSelected: [],
      otherFilters: [],
      todayFillDetail: {},
      activeDataId: '',
      channelTaskCode: '',
      showEdit: false,
      showDetail: false,
      nowTime,
      searchConfig: [
        { label: '门店', prop: 'shopCode', type: 'dialog',
          config: {
            defaultProps: { label: 'name', value: 'code' }
          },
          dialogConfig: {
            title: '门店',
            interfacePath: '/select-service/api/v1/shop/page',
            setting: [{ prop: 'code', title: '编码', width: 120 }, { prop: 'name', title: '名称', width: 250 }]
          }
        },
        { label: '客户经理', prop: 'customerManagerCode', type: 'dialog',
          config: {
            defaultProps: { label: 'userName', value: 'account' },
            apiHeader: { }

          },
          dialogConfig: {
            title: '客户经理',
            interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/user/domainMarketingUser/page`,
            setting: [{ prop: 'account', title: '编码', width: 120 }, { prop: 'userName', title: '名称', width: 250 }]
          }
        },
        { label: '办事处', prop: 'officeCode', type: 'dialog',
          config: {
            defaultProps: { label: 'name', value: 'code' }
          },
          dialogConfig: {
            title: '办事处',
            interfacePath: '/select-service/api/v1/organization/page',
            filtersRaw: [{ 'id': 'isOffice', 'property': 'isOffice', 'value': '1', 'operator': '=' }],
            setting: [{ prop: 'code', title: '编码', width: 120 }, { prop: 'name', title: '名称', width: 250 }]
          }
        },
        { label: '责任市场', prop: 'dutyMarket', type: 'text', placeholder: '', filter: true },
        {
          type: 'select',
          prop: 'isHaveProgress',
          label: '是否有进展',
          config: {
            selectData: [
              { label: '是', value: '1' },
              { label: '否', value: '0' }
            ] }
        }, {
          type: 'select',
          prop: 'schedule',
          label: '整体进度',
          filter: true,
          config: {
            filterable: false,
            remoteUrl: '/data-dict/api/v2/dictionary/OVERALL_PROGRESS?appCode=slm&domainCode=marketing',
            defaultProps: { label: 'dictName', value: 'dictCode' }
          }
        },
        {
          type: 'select',
          prop: 'isTodayFillReport',
          label: '今日是否填写进度汇报',
          config: {
            selectData: [
              { label: '是', value: '1' },
              { label: '否', value: '0' }
            ] }
        }
      ],
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/channelTask/page`,
        buttonGroupCode: 'default',
        hideSearchBar: true,
        tabIndex: 0,
        pageSize: 10,
        order: 'desc',
        // 表格字段动态配置
        setting: [
          {
            prop: 'officeName',
            label: '办事处',
            minWidth: '200',
            className: 'btn-green',
            isButton: true,
            clickFun: this.handleDetail
          },
          {
            prop: 'customerManagerCode',
            label: '客户经理',
            minWidth: '140',
            render: function(createElement, rows) {
              if (rows.customerManagerCode || rows.customerManagerName) {
                return (<div>{ rows.customerManagerName + rows.customerManagerCode }</div>
                )
              }
              return ''
            }
          },
          {
            prop: 'customerManagerPhone',
            label: '联系方式',
            minWidth: '140'
          },
          {
            prop: 'isContinueLastMonthMarket',
            label: '是否延续上月市场',
            minWidth: '120',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            }
          },
          {
            prop: 'dutyMarket',
            label: '责任市场',
            minWidth: '110'
          }, {
            prop: 'shopCode',
            label: '门店编码',
            minWidth: '120'
          }, {
            prop: 'shopName',
            label: '门店名称',
            minWidth: '120'
          },
          {
            prop: 'reportPicType',
            label: '报图类型',
            minWidth: '110',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'REPORT_TYPE'
            }
          },
          {
            prop: 'taskType',
            label: '任务类型',
            minWidth: '110',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'CHANNEL_TASK_TYPE'
            }
          },
          {
            prop: 'isHaveProgress',
            label: '当前是否有进展',
            minWidth: '120',
            className: 'btn-green',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            }
          },
          {
            prop: 'schedule',
            label: '整体进度',
            type: 'select',
            minWidth: '110',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'OVERALL_PROGRESS'
            }
          },

          {
            prop: 'isFinishResolve',
            label: '是否完成分解任务',
            minWidth: '145',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            }
          },
          {
            prop: 'thisMonthActualSurveyTime',
            label: '本月实际测绘数',
            minWidth: '160'
          },
          {
            prop: 'thisMonthSurveyConstCode',
            label: '本月测绘项目号',
            minWidth: '130'
          },
          {
            prop: 'isSurveyAndMarketConsisten',
            label: '实际测绘与任务市场是否一致',
            minWidth: '145',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            }
          },
          {
            prop: 'isAccountingThisMonth',
            label: '是否核算本月任务',
            minWidth: '130',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            }
          },
          {
            prop: 'remark',
            label: '备注',
            minWidth: '130'
          }
        ],
        btnList: this.isProduction ? null : [{
          buttonName: '新增',
          outerFlag: true,
          optCode: 'add'
        },
        {
          buttonName: '编辑',
          outerFlag: true,
          optCode: 'edit'
        },
        {
          buttonName: '导入',
          outerFlag: true,
          optCode: 'import'
        },
        {
          buttonName: '导出',
          outerFlag: true,
          optCode: 'export'
        },
        {
          buttonName: '每日填报',
          outerFlag: true,
          optCode: 'dailyFill'
        }
        ]
      }
    }
  },
  computed: {
    exportConfig() {
      return [{
        code: 'export',
        name: '渠道任务跟进',
        dataApi: '/slm-admin/api/v1/channelTask/export',
        selectedRows: this.tableSelected,
        paramsRaw: {},
        filtersRaw: this.otherFilters,
        queryField: 'id'
      }
      // todo
      // {
      //   code: 'exportTemplate',
      //   name: '渠道任务跟进模板',
      //   async: false,
      //   templateMethod: 'post',
      //   templateApi: '/slm-admin/api/v1/shopUpgrade/export?type=1'
      // }
      ]
    },
    fileImportConfig() {
      return [{
        code: 'importNew',
        name: '新增渠道任务跟进',
        async: false,
        apiUrl: '/slm-admin/api/v1/channelTask/importExcel'
      }]
    }
  },
  async  created() {
  },
  methods: {
    handleDetail(row) {
      this.activeDataId = row.id
      this.showDetail = true
    },
    // 清空搜索数据
    clearSearch() {
    },
    // 设置表格多选行高亮
    tableRowClassName({ row, rowIndex }) {
      const filterArr = this.tableSelected.filter(item => item.id === row.id)
      return filterArr.length > 0 ? 'selected-highlight' : ''
    },
    refreshTable(flag) {
      this.$refs.refTable.initTableData(!!flag)
    },
    // 获取搜索条件
    handleSearch(data) {
      this.otherFilters = [...data.filtersRaw]
      this.$nextTick(() => {
        this.$refs.refTable.initTableData()
      })
    },
    btnOperate(flag) {
      switch (flag) {
        case 'add':
          this.handleEdit()
          break
        case 'edit':
          if (!this.singleJudge(this.tableSelected, '编辑', true)) {
            return
          }
          this.handleEdit(this.tableSelected[0])
          break
        case 'import':
          this.handleImport()
          break
        case 'export':
          this.handleExport()
          break
        case 'dailyFill':
          if (!this.singleJudge(this.tableSelected, '新增', true)) {
            return
          }
          if (!this.tableSelected[0].channelTaskCode) {
            this.$message.warning('没有渠道任务号，不能填报')
            return
          }
          this.handleAdd()
          break

        default:
          break
      }
    },
    // 客户经理新增每日填报
    handleAdd() {
      queryDailyFill(this.tableSelected[0].channelTaskCode).then(res => {
        if (res.success) {
          const tempArr = res.data.records.filter(v => v.fillTime && v.fillTime.slice(0, 10) === this.nowTime(true))
          if (tempArr.length > 0) {
            const { channelTaskCode = '',
              id = '',
              isHaveProgress = undefined,
              haveIntentionDealer = undefined,
              mapReportRate = '',
              negotiationSituationDetailed = '',
              planSurveyTime = '',
              planReportPicTime = '' } = tempArr[tempArr.length - 1]
            this.todayFillDetail = { channelTaskCode,
              id,
              isHaveProgress,
              haveIntentionDealer,
              mapReportRate,
              negotiationSituationDetailed,
              planSurveyTime,
              planReportPicTime }
          } else {
            this.todayFillDetail = {
              channelTaskCode: '',
              id: '',
              isHaveProgress: undefined,
              haveIntentionDealer: undefined,
              mapReportRate: '',
              negotiationSituationDetailed: '',
              planSurveyTime: '',
              planReportPicTime: ''
            }
          }
          this.activeDataId = this.tableSelected[0].id
          this.channelTaskCode = this.tableSelected[0].channelTaskCode
          this.showAddItem = true
        }
      })
    },
    // 新增/编辑
    handleEdit(data) {
      if (data && data.id) {
        this.activeDataId = data.id
      } else this.activeDataId = ''
      this.showEdit = true
    },
    // 导出
    handleExport() {
      this.exportVisible = true
    },
    // 导入
    handleImport() {
      this.importVisible = true
    },
    selectionChangeHandle(rows) {
      this.tableSelected = rows
    }
  }
}
</script>
